#include <iostream>
#include <signal.h>
#include "../comm/httplib.h"
#include "oj_control.hpp"

using namespace ns_control;
using namespace httplib;

static Control *ctrl_ptr = nullptr;

void Recovery(int signo)
{
    ctrl_ptr->RecoverMachine();
}

int main()
{
    signal(SIGQUIT,  Recovery);

    Server svr;
    Control ctrl;

    ctrl_ptr = &ctrl;

    svr.Get("/all_questions", [&ctrl](const Request &req, Response &resp){
        // 返回一张包含所有提米的html网页
        std::string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html, "text/html; charset=utf-8");
    });

    // 用户根据题目编号，获取题目的内容
    svr.Get(R"(/question/(\d+))", [&ctrl](const Request &req, Response &resp){
        std::string number = req.matches[1];
        std::string html;
        ctrl.Question(number, &html);
        resp.set_content(html, "text/html; charset=utf-8");
    });

    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp){
        std::string number = req.matches[1];
        std::string in_json = req.body;
        std::string out_json;
        ctrl.Judge(number, in_json, &out_json);
        resp.set_content(out_json, "application/json; charset=utf-8");
    });

    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0", 8080);

    return 0;
}